import re
import copy
from yxlog.logger import get_logger
from handle.document import ParseOfDocuments
from common.time_convertor import TimeConverter
from handle.parse_config import MAPPING_STRUCTURE

logger = get_logger()
TC = TimeConverter()


def post_process(result, image):
    if not result:
        return ""
    title, title_ids, ocr_type = document_type(result)
    init_result = {
        "subCertificateName": title,
        "originalData": "\n".join([item["text"] for item in result]),
        "certificateName": "UNKNOWN",
    }
    if not ocr_type:
        return init_result

    params = copy.deepcopy(ocr_type)
    params["subCertificateName"] = title
    params["usedIds"] = title_ids
    params["image"] = image
    params["ocrResult"] = result
    parse_obj = ParseOfDocuments(**params)
    result = parse_obj.parse_structure_data()
    return result


def document_type(result):
    title_ids = []
    for i in range(len(result)):
        for item in MAPPING_STRUCTURE:
            _match = re.search(item["subCertificateName"], result[i]["text"])
            if not _match:
                continue
            title = _match.group()
            title_ids.append(i)
            count = i-1
            while count >= 0:
                sub_title = re.search("中华人民共和国|国家食品药品监督管理局", result[count]["text"])
                if sub_title:
                    title_ids.append(count)
                    title = sub_title.group() + title
                    break
                count -= 1
            return title, title_ids, item

    return "", [], None
